<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.itaoke.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  Caption <Caption@163.com> QQ 1674653
// +----------------------------------------------------------------------
// + 用于爱淘客 的定时更新优惠券数据是否有效 itaoke.ORG

namespace Home\Controller;
use Common\Controller\FirstendController;

class AutorefreshController extends FirstendController {

	public function _initialize() {
		parent :: _initialize();
		$this -> item_mod = M('Items');
		$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
		$this->_tbconfig = unserialize($api_config);
	
	}
	
	public function index(){
		$auth=I('auth','');
		if($auth!=C('itk_auto_auth'))
			return;
		
		// 开始刷新
		if(C('itk_auto_refresh',null,0)==1)
			$this->autoUpdate();
	}
	
	private function autoUpdate(){
		$where['isq']=1;
		$where['coupon_end_time']= array('EGT',time());						//只批量处理时间正常的优惠券
		$where['status'] ='underway';
		
		$items = $this ->item_mod->where($where)->select();
		$allcount=count($items);
		if ($allcount==0) {
			return ;
		}
		for($i=0;$i<$allcount;$i++){
			$isAuth=$this->trueAutoUpdate($items[$i]['id'],$items[$i]['num_iid'],$items[$i]['quanurl']);
			if($isAuth==-1)
				break;
		}
	}
	
	private function trueAutoUpdate($id,$num_iid,$qwurl){
		
		$tb_top = $this->_get_top();
		$req = $tb_top->load_api('ItaokeItemUpdateRequest');
		$req->putOtherTextParam('num_iid',$num_iid );				// 设置商品ID
		$req->putOtherTextParam('quanurl',$qwurl );
		$resp = (array)$tb_top->execute($req);
		if($resp['status'] != '0000')
		{
			return -1;
		}else{
			$_res=$resp['data'];

			if($_res['quan_surplus']==0){		// 过期
				$_res['status']='sellout';
				unset($_res['quan_receive']);
			}
			
			if($_res['volume']==''){			// 为空代表 挂了
				$_res['status']='sellout';
				unset($_res['volume']);
			}
			unset($_res['quan_receive']);
			unset($_res['quan_surplus']);
			
			$this->item_mod->where(array('id'=>$id))->save($_res);
		}
	}
	
	private function _get_top() {
		vendor('Itaoke.TopClient');
		vendor('Itaoke.RequestCheckUtil');
		vendor('Itaoke.Logger');
		$top = new \TopClient;
		$top->appkey = $this->_tbconfig['app_key'];
		$top->secretKey = $this->_tbconfig['app_secret'];
		return $top;
	}
}